<?php
/**
 * Author: yann
 * QQ: 9197313
 * Date: 2018/12/14 0014
 * Time: 上午 10:53
 */

namespace app\model;


use app\util\Tools;

class AuthRule extends Base
{

    public function getList($group_id){
        try{
            $list = Menu::order('sort', 'ASC')->select()->toArray();
            $list = Tools::listToTree($list);
            $rules = [];
            if ($group_id) {
                $rules = $this->where(['group_id' => $group_id])->select()->toArray();
                $rules = array_column($rules, 'url');
            }
            $newList = self::buildList($list, $rules);
            return $newList;
        }catch (\Exception $e){
            return [];
        }
    }

    /**
     * 编辑权限细节
     * @param $postData
     * @return bool
     * @throws \think\exception\PDOException
     */
    public function editRule($postData) {
        $needAdd = [];
        $this->startTrans();
        try {
            if ($postData['rules']) {
                $has = $this->where(['group_id' => $postData['id']])->select()->toArray();
                $hasRule = array_column($has, 'url');
                $needDel = array_flip($hasRule);
                foreach ($postData['rules'] as $key => $value) {
                    if (!empty($value)) {
                        if (!in_array($value, $hasRule)) {
                            $data['url'] = $value;
                            $data['group_id'] = $postData['id'];
                            $needAdd[] = $data;
                        } else {
                            unset($needDel[$value]);
                        }
                    }
                }
                if (count($needAdd)) {
                    $this->saveAll($needAdd);
                }
                if (count($needDel)) {
                    $urlArr = array_keys($needDel);
                    $this->where([
                        ['group_id' ,'=', $postData['id']],
                        ['url' ,'in', $urlArr]
                    ])->delete();
                }

            }
            unset($postData['rules']);
            AuthGroup::update($postData);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * @param $list
     * @param $rules
     * @return array
     */
    private function buildList($list, $rules) {
        $newList = [];
        foreach ($list as $key => $value) {
            $newList[$key]['title'] = $value['name'];
            $newList[$key]['key'] = $value['url'];
            if (isset($value['_child'])) {
                $newList[$key]['expand'] = true;
                $newList[$key]['children'] = self::buildList($value['_child'], $rules);
            } else {
                if (in_array($value['url'], $rules)) {
                    $newList[$key]['checked'] = true;
                }
            }
        }

        return $newList;
    }

}
